package com.blog.common.exception;

import com.blog.common.constant.ResultCode;
import com.blog.common.result.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.List;

/**
 * 描述： 处理统一异常的handler
 */
@ControllerAdvice
public class GlobalExceptionHandler {
    private final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    /**
     * 系统异常
     *
     * @param ex
     * @return
     */
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public Object handleException(Exception ex) {
        logger.error("Default Exception", ex);
        return Result.error(ResultCode.INTERNAL_SERVER_ERROR);
    }

    /**
     * 业务异常
     *
     * @param ex
     * @return
     */
    @ExceptionHandler(BlogException.class)
    @ResponseBody
    public Object handleBlogException(BlogException ex) {
        logger.error("Blog Exception", ex);
        return Result.error(ex.getCode(),ex.getMsg());
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    public Result handleMethodArgumentNotValidException(MethodArgumentNotValidException ex) {
        logger.error("MethodArgumentNotValidException", ex);
        return handleBindingResult(ex.getBindingResult());
    }

    private Result handleBindingResult(BindingResult bindingResult) {
        // 把异常处理为对外暴露的提示
        List<String> list = new ArrayList<>();
        if (bindingResult.hasErrors()){// 是否包含错误
            List<ObjectError> allErrors = bindingResult.getAllErrors();
            for (ObjectError objectError : allErrors){
                String errMsg = objectError.getDefaultMessage();
                list.add(errMsg);
            }
        }
        if (list.size() == 0){
            return Result.error(ResultCode.REQUEST_PARAM_ERROR);
        }
        return Result.error(ResultCode.REQUEST_PARAM_ERROR,list.toString());
    }
}
